package com.dream.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.commons.result.Tree;
import com.dream.commons.shiro.ShiroUser;
import com.dream.commons.utils.TreeUtils;
import com.dream.mapper.ResourceMapper;
import com.dream.mapper.RoleMapper;
import com.dream.mapper.RoleResourceMapper;
import com.dream.mapper.UserRoleMapper;
import com.dream.model.Organization;
import com.dream.model.Resource;
import com.dream.model.RoleResource;
import com.dream.model.DTO.LayuiTreeDto;
import com.dream.model.DTO.MenuDto;
import com.dream.model.DTO.resourceDto.ResourceTreeDto;
import com.dream.service.ResourceService;

/**
 *
 * Resource 表数据服务层接口实现类
 *
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    private static final int RESOURCE_MENU = 0; // 菜单

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    /**
     * 封装权限属树形菜单
     */
    @Override
    public List<Tree> selectTree(ShiroUser shiroUser) {
        List<Tree> trees = new ArrayList<Tree>();
        // shiro中缓存的用户角色
        Set<String> roles = shiroUser.getRoles();
        if (roles == null) {
            return trees;
        }
        // 如果有超级管理员权限
        if (roles.contains("admin")) {
            List<Resource> resourceList = this.selectByType(RESOURCE_MENU);
            if (resourceList == null) {
                return trees;
            }
            for (Resource resource : resourceList) {
                Tree tree = new Tree();
                tree.setId(resource.getId());
                tree.setPid(resource.getPid());
                tree.setText(resource.getName());
                tree.setIconCls(resource.getIcon());
                tree.setAttributes(resource.getUrl());
                tree.setOpenMode(resource.getOpenMode());
                tree.setState(resource.getOpened());
                trees.add(tree);
            }
            return trees;
        }
        // 普通用户
        List<Long> roleIdList = userRoleMapper.selectRoleIdListByUserId(shiroUser.getId());
        if (roleIdList == null) {
            return trees;
        }
        List<Resource> resourceLists = roleMapper.selectResourceListByRoleIdList(roleIdList);
        if (resourceLists == null) {
            return trees;
        }
        for (Resource resource : resourceLists) {
            Tree tree = new Tree();
            tree.setId(resource.getId());
            tree.setPid(resource.getPid());
            tree.setText(resource.getName());
            tree.setIconCls(resource.getIcon());
            tree.setAttributes(resource.getUrl());
            tree.setOpenMode(resource.getOpenMode());
            tree.setState(resource.getOpened());
            trees.add(tree);
        }
        return trees;
    }	
    
    public List<Resource> selectByType(Integer type) {
        EntityWrapper<Resource> wrapper = new EntityWrapper<Resource>();
        Resource resource = new Resource();
        wrapper.setEntity(resource);
        wrapper.addFilter("resource_type = {0}", type);
        wrapper.orderBy("seq");
        return resourceMapper.selectList(wrapper);
    }
  
    /**
     * 左侧菜单
     */
	@Override
	public List<MenuDto> getLeftMenu(ShiroUser shiroUser) {
		long userId = shiroUser.getId();
		List<MenuDto> fatherMenuList = resourceMapper.getFatherMenuByUserId(userId);
		for (MenuDto menuDto : fatherMenuList) {
			List<MenuDto> childMenuList = resourceMapper.getChildMenuByPid(menuDto.getId());
			menuDto.setChildren(childMenuList);
		}
		return fatherMenuList;
	}
    
    /**
     * 资源树形结构
     * @return
     */
	@Override
	public List<LayuiTreeDto> selectLayuiTree(String id) {
		List<RoleResource> roleResourceList = null;
		if (id != null) {
			EntityWrapper<RoleResource> wrapper = new EntityWrapper<RoleResource>();
			wrapper.eq("role_id", id);
			roleResourceList = roleResourceMapper.selectList(wrapper);
		}
		List<Resource> resourceList = selectTreeGrid();
		//转化treeDto
		List<LayuiTreeDto> trees = new ArrayList<LayuiTreeDto>();
		if (resourceList != null && resourceList.size() > 0) {
			for (Resource resource : resourceList) {
				LayuiTreeDto tree = new LayuiTreeDto();
				tree.setId(resource.getId().toString());
				tree.setName(resource.getName());
				Long pid = resource.getPid();
				if (pid != null) {
					tree.setParentId(pid.toString());
				}
				trees.add(tree);
			}
		}	
		//选中该数据已选权限
		if (trees != null && trees.size() > 0) {
			if (roleResourceList != null && roleResourceList.size() > 0) {
				for (LayuiTreeDto layuiTreeDto : trees) {
					for (RoleResource roleResource : roleResourceList) {
						if(roleResource.getResourceId() == Long.parseLong(layuiTreeDto.getId())){
							layuiTreeDto.setChecked(true);
						}
					}
				}
			}
		}
		//封装tree格式
		List<LayuiTreeDto> treeString = TreeUtils.formatTree(trees, false);
		return treeString;
	}
    
    /**
     * 查询所有权数据
     * @return
     */
    @Override
    public List<Resource> selectTreeGrid() {
        EntityWrapper<Resource> wrapper = new EntityWrapper<Resource>();
        wrapper.orderBy("seq");
        return resourceMapper.selectList(wrapper);
    }

    /**
     * 所有资源treeTable
     */
	@Override
	public List<ResourceTreeDto> selectLayuiTreeTable() {
		List<Resource> resourceList =  this.selectTreeGrid();
		List<ResourceTreeDto> treeTables = new ArrayList<ResourceTreeDto>();
		if (resourceList != null && resourceList.size() > 0) {
			for (Resource resource : resourceList) {
				ResourceTreeDto treeTable = new ResourceTreeDto();
				treeTable.setId(resource.getId().toString());
				treeTable.setName(resource.getName());
				treeTable.setCreateTime(resource.getCreateTime());
				treeTable.setResourceType(resource.getResourceType());
				treeTable.setUrl(resource.getUrl());
				treeTable.setSeq(resource.getSeq());
				treeTable.setIcon(resource.getIcon());
				Long pid = resource.getPid();
				if (pid != null) {
					treeTable.setParentId(pid.toString());
				}
				treeTables.add(treeTable);
			}
		}	
		//封装tree格式
		List<ResourceTreeDto> treeString = TreeUtils.formatTree(treeTables, false);
		return treeString;
	}
    
    
}